﻿import mx.utils.Delegate;

import com.gamemeal.physics.Particle;
import com.gamemeal.physics.PhyObj;
import com.gamemeal.physics.Point3;
import com.gamemeal.physics.PullForce;
import com.gamemeal.physics.TorqueForce;
import com.mixmedia.mx.Event;
import com.mixmedia.mx.MovieClipEvt;

/**
 * @author Colin
 */
class com.gamemeal.physics.PhyObjDragable extends PhyObj{
	public var centreOfMass:Particle;
	private var pointOfPress : Point3;
	private var thrust:PullForce;

	private var isDown : Boolean;
	private var torque : TorqueForce;
	private var mc:MovieClip;

	
	public function PhyObjDragable(mc:MovieClipEvt) {
		this.mc = mc.mc;

		centreOfMass = new Particle();
		centreOfMass.d.x = this.mc._x;
		centreOfMass.d.y = this.mc._y;
		pointOfPress = new Point3(0,0,0);
		thrust = new PullForce();
		torque = new TorqueForce();
		centreOfMass.addForce(thrust);
		centreOfMass.addForce(torque);
		
		mc.addEventListener(Event.ENTERFRAME,Delegate.create(this,update));
		mc.addEventListener(Event.CLICK,Delegate.create(this,onPress));
		mc.addEventListener(Event.RELEASE,Delegate.create(this,onRelease));
		mc.mc.useHandCursor = true;
	}

	public function update(time:Number){
		if(isDown){
			var mcMouse = getMousePositionWithRotationFix();			
			torque.vR = pointOfPress;
			torque.vT.x = (mcMouse.x-pointOfPress.x)/5;
			torque.vT.y = (mcMouse.y-pointOfPress.y)/5;

			thrust.setForce((mcMouse.x-pointOfPress.x),(mcMouse.y-pointOfPress.y),0);

		}
		centreOfMass.update(0.2);
		mc._x = centreOfMass.d.x;
		mc._y = centreOfMass.d.y;
		mc._rotation = centreOfMass.θ;
	}

	public function onPress(){
		var mcMouse = getMousePositionWithRotationFix();

		pointOfPress.x = mcMouse.x;
		pointOfPress.y = mcMouse.y;
		isDown = true;
	}
	
	private function getMousePositionWithRotationFix():Object{
		var posMC = {x:0,y:0};
		mc.localToGlobal(posMC);
		return {x:_root._xmouse - posMC.x,y:_root._ymouse-posMC.y};	
	}
	
	public function onRelease(){
		isDown = false;
	}
}